#!/usr/bin/perl

# USAGE:
# ./manifest_filter.pl [--<flavor>] manifest.json
# Chrome versions supported:
# stable  No changes made (DEFAULT)
# dev     Add "experimental" and "storage" permission
# 17      Use "background_page" instead of "background"

use JSON;
use Data::Dumper;

$flavor = shift @ARGV;

@lines = <>;
$manifest_text = join '', @lines;

$manifest = decode_json $manifest_text;

if($flavor eq '--dev')
{
	push ${$manifest}{'permissions'}, 'experimental';
	push ${$manifest}{'permissions'}, 'storage';
#	push ${$manifest}{'permissions'}, 'declarative';
	push ${$manifest}{'permissions'}, 'declarativeWebRequest';
	push ${$manifest}{'permissions'}, 'alarms';
	${$manifest}{'name'} = "Riverside Plus (Dev)";
}
elsif($flavor eq '--17')
{
	delete ${$manifest}{'manifest_version'};
	#That seems to be the very first version to support chrome.cookies
	${$manifest}{'minimum_chrome_version'} = "6.0.469.0";
	${$manifest}{'background_page'} = 'bg.html';
	$permissions = ${$manifest}{'permissions'};
	# Add webNavigation permission for Chrome 16
	push @{$permissions}, "webNavigation";

	# Make sure that background scripts are included in bg.html so that Chrome
	# 17- will load them. The "background" key won't be removed since unknown
	# manifest keys (as well as permissions) will be silently ignored in the
	# previous versions of Chrome.
	my $background_scripts = ${$manifest}{'background'}{'scripts'};
	die "Failed to open bg.html" unless(open BG_HTML, ">src/bg.html");
	print BG_HTML "<html><head>\n<title>Background page for Riverside Plus</title>\n";
	print BG_HTML '<meta http-equiv="content-type" content="text/html; charset=utf-8">';
	print BG_HTML "\n";
	for(@{$background_scripts})
	{
		print BG_HTML "<script type=\"text/javascript\" src=\"$_\"></script>\n";
	}
	print BG_HTML "</head><body></body></html>\n";
	close BG_HTML;
	delete ${$manifest}{'background'};
}
elsif($flavor eq '--stable')
{
	my $version = ${$manifest}{'version'};
	${$manifest}{'version'} = $version . '1';
	# HACK HACK See description in manifest.json
}

print JSON->new->utf8->pretty(true)->encode($manifest);

